/*
 * Copyright (C) 2011, EADS France
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */
package xowl.interpreter.adapter;

/**
 *
 * @author Laurent WOUTERS
 */
public class ClassObserverLink<T> extends xowl.interpreter.observers.ClassObserver {
    private ClassObserver<T> observer;
    private xowl.interpreter.Repository repository;
    private java.lang.Class<T> tClass;

    public ClassObserverLink(xowl.lang.runtime.Class _class, xowl.interpreter.Repository repository, java.lang.Class<T> tClass, ClassObserver<T> observer) {
        super(_class);
        this.observer = observer;
        this.repository = repository;
        this.tClass = tClass;
    }

    @Override public void onNewInstance(xowl.lang.runtime.Individual individual) {
        if (individual instanceof xowl.lang.owl2.AnonymousIndividual)
            return;
        xowl.lang.runtime.NamedIndividual ind = (xowl.lang.runtime.NamedIndividual)individual;
        xowl.lang.runtime.Entity entity = ind.getInterpretationOf();
        try {
            java.lang.reflect.Method method = tClass.getMethod("get", xowl.interpreter.Repository.class, xowl.lang.runtime.Entity.class);
            T t = (T)method.invoke(null, repository, entity);
            observer.onNewInstance(t);
        }
        catch (java.lang.NoSuchMethodException ex) {}
        catch (java.lang.IllegalAccessException ex) {}
        catch (java.lang.IllegalArgumentException ex) {}
        catch (java.lang.SecurityException ex) {}
        catch (java.lang.reflect.InvocationTargetException ex) {}
    }

    @Override public void onDestroyInstance(xowl.lang.runtime.Individual individual) {
        if (individual instanceof xowl.lang.owl2.AnonymousIndividual)
            return;
        xowl.lang.runtime.NamedIndividual ind = (xowl.lang.runtime.NamedIndividual)individual;
        xowl.lang.runtime.Entity entity = ind.getInterpretationOf();
        try {
            java.lang.reflect.Method method = tClass.getMethod("get", xowl.interpreter.Repository.class, xowl.lang.runtime.Entity.class);
            T t = (T)method.invoke(null, repository, entity);
            observer.onDestroyInstance(t);
        }
        catch (java.lang.NoSuchMethodException ex) {}
        catch (java.lang.IllegalAccessException ex) {}
        catch (java.lang.IllegalArgumentException ex) {}
        catch (java.lang.SecurityException ex) {}
        catch (java.lang.reflect.InvocationTargetException ex) {}
    }
}
